package com.skanda.auth.controller;

import com.skanda.common.Constants.CommonConstant;
import com.skanda.common.entity.*;
import com.skanda.common.feign.IUserClient;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.codec.Charsets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "认证模块")
@RequestMapping("/auth")
@RestController
public class AuthController {

    @Autowired
    private IUserClient userClient;

    @PostMapping("token")
    @ApiOperation(value = "获取认证token", notes = "传入账号:account,密码:password")
    public R<AuthInfo> token(@ApiParam(value = "账号") @RequestParam(required = false) String account,
                             @ApiParam(value = "密码") @RequestParam(required = false) String password) {
        UserInfo userInfo = userClient.userInfo(account,password).getData();
        if(userInfo!=null && userInfo.getUser()!=null){
          User user = userInfo.getUser();
          //设置jwt参数
          Map<String, String> userMap = new HashMap<>(16);
          userMap.put(CommonConstant.USER_ID, user.getId()+"");
          userMap.put(CommonConstant.USER_NAME, user.getName());
            userMap.put(CommonConstant.ROLE_ID, String.valueOf(user.getRoleId()));
            userMap.put(CommonConstant.ROLE_NAME, userInfo.getRoles().get(0));
          userMap.put(CommonConstant.DEPT_ID, user.getDeptId()+"");

          //生成签名密钥
          byte[] apiKeySecretBytes = CommonConstant.SIGN_KEY.getBytes(Charsets.UTF_8);
          SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

          long nowMillis = System.currentTimeMillis();
          Date now = new Date(nowMillis);
          Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

          //添加构成JWT的类
          JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")
                  .setIssuer("issuser")
                  .setAudience("audience")
                  .signWith(signingKey);
          //设置JWT参数
          userMap.forEach(builder::claim);

          //设置应用id
          builder.claim("etl","etl-client");

          //添加Token过期时间
          long expireMillis = 3600*1000;
          long expMillis = nowMillis + expireMillis;
          Date exp = new Date(expMillis);
          builder.setExpiration(exp).setNotBefore(now);

          // 组装Token信息
          TokenInfo tokenInfo = new TokenInfo();
          tokenInfo.setToken(builder.compact());
          tokenInfo.setExpire((int) expireMillis / 1000);
          AuthInfo authInfo = new AuthInfo();
          authInfo.setUserId(user.getId());
          authInfo.setAccessToken(builder.compact());
          authInfo.setExpiresIn(expMillis);
          authInfo.setUserName(user.getName());

          return R.data(authInfo);
      }
        return R.fail(); // R.data(TokenUtil.createAuthInfo(userInfo));
    }

}
